import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by ku on 2019/8/2.
 * pdf to png-image.
 * use pdfbox-2.0.16.jar and fontbox-2.0.16.jar
 * and commons-logging-1.2.jar //防止报错main线程异常-java.lang.NoClassDefFoundError：org/apache/commons/logging/logFactory
 */
public class PdfToImage {
    String pdfFileName = null;//设置全局pdf文件名默认为空
    public String toImage() {
        String pdfFilePath = choosePdfFile();//pdf文件路径加名称
        if (pdfFilePath == null) {
            System.out.println("未正确选择pdf文件，操作结束。");
            return "fail";
        }
        try {
            File pdfFile = new File(pdfFilePath);
            PDDocument document = PDDocument.load(pdfFile);
            PDFRenderer renderer = new PDFRenderer(document);
            System.out.println("pdf文件就绪，开始转换。。。");
            int page = document.getNumberOfPages();
            Date nowDate = new Date();
            SimpleDateFormat timeFormat = new SimpleDateFormat ("yyyyMMddhhmmss-");
            String  timeStamp = timeFormat.format(nowDate);//格式化时间做后缀
            String pngDir = setPngDirectory();//png图片保存路径文件夹
            for (int i = 0; i < page; i++) {
                BufferedImage image = renderer.renderImage(i, 2.5f);//缩放比例2.5，默认DPI是72；
                File pngPathName = new File(pngDir+pdfFileName+timeStamp+(i+1)+ ".png");
                if (!pngPathName.getParentFile().exists()) { //判断文件目录是否存在
                    if (!pngPathName.getParentFile().mkdirs()) { //判断创建目录是否成功
                        System.out.println("png图片保存目录创建失败，请重试！");
                        return "fail";
                    }
                }
                ImageIO.write(image, "PNG", pngPathName);
                System.out.println("第"+(i+1)+"页已完成，共"+page+"页。");
            }
            System.out.println("恭喜！pdf转换为png图片成功！");
        } catch (IOException e) {
            System.out.println(":(  T_T  sad...！转换失败！请重试！");
            e.printStackTrace();
        }
        return "success";

    }


    /*手动选择pdf源文件*/
    String choosePdfFile(){
        //过滤文件扩展名，显示所查找文件为.pdf的所有文件
        FileNameExtensionFilter fnef = new FileNameExtensionFilter("*.pdf","pdf");
        JFileChooser jfc = new JFileChooser();
        jfc.setFileFilter(fnef);//设置个文件筛选器，按照上边的扩展名筛选。
        jfc.setMultiSelectionEnabled(false);//禁止多选

        int returnVal = jfc.showOpenDialog(jfc);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            /*获取pdf文件路径及名称*/
            File pdfFile = jfc.getSelectedFile();//手动选择文件
            String pdfFilePath = pdfFile.getPath();//文件路径-包含全部路径和文件名
            pdfFileName = pdfFile.getName();//包含.pdf后缀
            pdfFileName = pdfFileName.substring(0,pdfFileName.length()-4);//截取不含.pdf后缀的文件名重新赋值给pdfFileName
            return pdfFilePath;
        } else {
            return null;
        }
    }

    /*手动设置png图片保存路径文件夹*/
    String setPngDirectory(){
        //获取桌面路径
        FileSystemView fsv = FileSystemView.getFileSystemView();
        String desktopDir = fsv.getHomeDirectory().getPath();
        String pngDir = desktopDir+"\\"+pdfFileName+"\\";//在桌面路径创建pdf文件命名的文件夹
        return pngDir;
    }
}
